package com.caiyi.tips.user.service.impl;

import com.caiyi.tips.core.VO.ResultVO;
import com.caiyi.tips.core.enums.ResultEnum;
import com.caiyi.tips.core.util.IdCreator;
import com.caiyi.tips.user.DTO.SmsDTO;
import com.caiyi.tips.user.bean.SmsBean;
import com.caiyi.tips.user.bean.TokenBean;
import com.caiyi.tips.user.bean.UserBean;
import com.caiyi.tips.user.exception.UserException;
import com.caiyi.tips.user.mapper.UserMapper;
import com.caiyi.tips.user.service.SmsService;
import com.caiyi.tips.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/*
 * @author Cliff.ZhouYang
 * @date 2017/11/8 15:59
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SmsService smsService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO register(UserBean userBean) {
        /**
         * 1.校验参数是否为空
         * 2.验证手机号
         * 3.生成cuserId (生成策略：uuid)
         * 4.入库
         * 6.返回token信息
         *
         */
        if (userBean.getUserType() == 0) {
            //推单用户
            if (userMapper.checkExpertExistPhone(userBean.getPhone()) > 0) {
                throw new UserException("手机号已存在");
            }
            if (userMapper.checkUserExistNickid(userBean.getPhone()) > 0) {
                throw new UserException("用户名已存在");
            }
        } else {
            //普通用户
            //验证手机号
            if (userMapper.checkUserExistPhone(userBean.getPhone()) > 0) {
                throw new UserException("手机号已存在");
            }
            //验证用户名
            if (userMapper.checkUserExistNickid(userBean.getPhone()) > 0) {
                throw new UserException("用户名已存在");
            }
        }
        this.checkYzm(userBean);
        this.createUser(userBean);
        TokenBean tokenBean = null;//this.createTokenBean(userDTO);
        return new ResultVO(ResultEnum.SUCCESS.getCode(), "注册成功", tokenBean);
    }

    @Override
    public void checkYzm(UserBean userBean) {
        SmsBean smsBean = new SmsBean();
        smsBean.setRandom(userBean.getRandom());
        smsBean.setYzmType(userBean.getYzmType());
        smsBean.setPhone(userBean.getPhone());
        smsBean.setUserType(userBean.getUserType());
        smsService.checkSmsYzm(smsBean);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserBean createUser(UserBean userBean) {
        //userBean.setCloginfrom(userBean.getCbelongValue());

        String userid = IdCreator.uuid();
        userBean.setUserid(userid);

        String password = userBean.getPassword();
        if (!StringUtils.isEmpty(password)) {
            password = DigestUtils.md5Hex(password);
            userBean.setPassword(password);
        }
        this.saveUser(userBean);
        return userBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveUser(UserBean userBean) {
        if (userBean.getUserType() == 0) {
            //普通用户
            return userMapper.saveExpert(userBean);
        } else {
            //推单用户
            return userMapper.saveUser(userBean);
        }
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public TokenBean createTokenBean(UserDTO userDTO) {
//
//        /**
//         * 校验是否注销用户
//         */
//        CancellationUserBean cancellationUserBean = new CancellationUserBean();
//        cancellationUserBean.setCuserId(userBean.getCuserId());
//        cancellationUserBean.setCancellationValue(userBean.getCloginfrom());
//        if (cancellationUserService.getCountByCuserIdAndCancellationValue(cancellationUserBean) > 0) {
//            throw new UserException(TokenCodeConstant.LOGIN_TOKEN_ACCOUNT_FORBIDDEN, "用户已经注销");
//        }
//
//        TokenBean token = new TokenBean();
//        String appId = UniqueStrCreator.createUniqueString(tokenConfigurationProperties.getAppidPrefix());
//        String accessToken = TokenGenerator.createToken(appId);
//        token.setAccessToken(accessToken);
//        token.setAppId(appId);
//        token.setCuserId(userBean.getCuserId());
//        token.setCloginfrom(userBean.getCloginfrom());
//        token.setExpiresin(tokenConfigurationProperties.getDefaultExpiresin());
//        token.setMobileType(userBean.getMobileType());
//        token.setCreateTime(new Date());
//        token.setCnickId(userBean.getCnickId());
//        tokenService.saveToken(token);
//        return token;
//    }
    @Override
    public ResultVO login(UserBean userBean) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO checkPhone(String phone, Integer type) {
        int ret;
        if (type== 0) {
            //推单用户
            ret = userMapper.checkUserExistPhone(phone);
        } else {
            //普通用户
            ret = userMapper.checkExpertExistPhone(phone);
        }
        if (ret == 0) {
            return ResultVO.okMsg("手机号未注册");
        }
        return ResultVO.fail(ResultEnum.USER_PHONE_ERROR.getCode(),"已注册手机号，请重新输入");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public  ResultVO checkNickid(String nickid , Integer type){
        int ret;
        if (type == 0) {
            //推单用户
            ret = userMapper.checkExpertExistNickid(nickid);
        } else {
            //普通用户
            ret = userMapper.checkUserExistNickid(nickid);
        }
        if (ret == 0) {
            return ResultVO.okMsg("用户名未注册");
        }
        return ResultVO.fail(ResultEnum.USER_NICKID_EXIST_ERROR.getCode(),"已注册用户名，请重新输入");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean  isExistPhone(String phone, Integer type) {
        int ret;
        if (type== 0) {
            //推单用户
            ret = userMapper.checkUserExistPhone(phone);
        } else {
            //普通用户
            ret = userMapper.checkExpertExistPhone(phone);
        }
        if (ret == 0) {
            return false;
            //return ResultVO.okMsg("手机号未注册");
        }
        return true;
       // return ResultVO.fail(ResultEnum.USER_PHONE_ERROR.getCode(),"已注册手机号，请重新输入");
    }

    @Override
    public void updateUserInfo (UserBean userBean){
        int  ret = userMapper.updateUserInfo(userBean);
        if (ret != 1) {
            throw new UserException(ResultEnum.USER_RESET_PWD_ERROR.getCode(), "重置密码失败");
        }
    }
}
